package com.zhiliao.demo1.spring;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;

/**
 * 作者： zhi-liao
 * 类的作用:
 * 类的创建时间： 2021/5/23 11:16
 */
public class SingletonSpring {
    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);
    private final static Predicate<Object> NOT_NULL_OBJECT = obj -> obj != null ? true : false;
    private final static Object NULL_OBJECT = new Object();


    /**
     * DefaultSingletonBeanRegistry
     * @param beanName
     * @param singletonFactory
     * @return
     */
    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
        synchronized (this.singletonObjects) {
            // 检查缓存中是否存在实例
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                try {
                    singletonObject = singletonFactory.getObject();
                } catch (Exception e) {

                }
                addSingleton(beanName, singletonObject);
            }
            return (NOT_NULL_OBJECT.test(singletonObject) ? singletonObject : null);
        }
    }

    //将对象添加到单例注册表
    protected void addSingleton(String beanName, Object singletonObject) {
        synchronized (this.singletonObjects) {
            this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
        }
        System.out.println(singletonObjects);
    }
}
